import { getArticleTableApi } from '@/api/cms/article/article'
import { ArticleListParam } from '@/api/cms/article/ArticleModel'
import { StatusCode } from '@/http/request'
import { formatDate } from '@/utils/filters'
import { onMounted, reactive, nextTick, ref, watch } from 'vue'
import { useRoute } from 'vue-router'

export default function useArticleTable() {
    const route = useRoute()

    // 定义列表查询的参数
    const listParam = reactive<ArticleListParam>({
        current_page: 1,
        page_size: 20,
        title: '',
        status: '1',
        total: 0
    })
    // 表格的高度
    const tableHeight = ref(0)

    // 表格数据
    const articleTable = reactive({
        list: []
    })
    // 获取表格数据
    const getArticleTable = async () => {
        let res = await getArticleTableApi(listParam)
        if (res && res.code == StatusCode.Success) {
            console.log('文章列表：', res.data.list)
            articleTable.list = res.data.list
            articleTable.list.forEach((item: any) => {
                item.created_at = formatDate(item.created_at)
            })
            listParam.total = res.data.total
        }
    }

    // 页容量改变时触发
    const sizeChange = (size: number) => {
        listParam.page_size = size
        getArticleTable()
    }

    // 页数改变时触发
    const currentChange = (page: number) => {
        listParam.current_page = page
        getArticleTable()
    }

    // 搜索
    const searchBtn = () => {
        getArticleTable()
    }
    // 重置
    const resetBtn = () => {
        listParam.title = ''
        listParam.status = '1'
        getArticleTable()
    }

    // 首次加载
    onMounted(() => {
        getArticleTable()
        nextTick(() => {
            tableHeight.value = window.innerHeight - 180
        })
    })

    watch(
        () => route.path,
        (to, from) => {
            // console.log('to=' + to + ' from=' + from)
            if (to == '/cms/article') {
                if (from == '/cms/article/add' || from == '/cms/article/edit') {
                    getArticleTable()
                }
            }
        }
    )

    return {
        listParam,
        resetBtn,
        searchBtn,
        tableHeight,
        articleTable,
        getArticleTable,
        sizeChange,
        currentChange
    }
}
